import {ref,computed} from 'vue';
import {defineStore} from "pinia";
import {loginsApi ,signupApi,getUserDetailApi} from "@/api/UserApi.js";
import { ElMessage } from 'element-plus'
import{useRouter} from "vue-router";

export const useUserStore = defineStore("user", ()=>{
    const token = ref("")
    const isLogin = ref(false)
    const userDetail = ref({})
    const changeIsLogin = computed(() => {
        isLogin.value = !isLogin.value
        return isLogin.value
    })
    const login =  (data) => {
        const response = loginsApi(data).then(response => {
            if(response.data.status === "success"){
                isLogin.value = true
                token.value = response.data.token
                ElMessage.error("登陆成功")
                useRouter().push('/')
                return true
            }
        }).catch(error => {
            return response.data
        })
        isLogin.value = false
        ElMessage.error("登陆失败")
        return false
    }
    const signup = (data) => {
        const response = signupApi(data).then(response => {
            if(response.data.status === "success"){
                isLogin.value = true
                ElMessage.error("注册成功，返回登录")
                useRouter().push('/')
                return true
            }
        }).catch(error => {
            return response.data
        })
        isLogin.value = false
        ElMessage.error("注册失败")
        return false
    }
    const getUserDetail = async (id) => {
        const response = await getUserDetailApi(id)
        userDetail.value = response.data
    }
    return {
        token,
        isLogin,
        userDetail,
        changeIsLogin,
        login,
        signup,
        getUserDetail
    }
},{
    persist: {
        enabled: true,
        strategies: localStorage,
        key: "userStore"
    }
})